package com.thssh.ui.lsn09.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

/**
 * @author zhangyugehu
 * @version V1.0
 * @date 2017/09/25
 * email: zhangyugehu@163.com
 */

public class BezierView extends View {


    private Paint mPaint;
    private Path mPath;
    private Point start;
    private Point end;
    private Point controller;

    public BezierView(Context context) {
        this(context, null);
    }

    public BezierView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BezierView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPath = new Path();
        initPoint();
    }

    private void initPoint() {
        start = new Point();
        end = new Point();
        controller = new Point();
        start.x = 100;
        start.y = 100;
        end.x = 700;
        end.y = 100;
        controller.x = 250;
        controller.y = 200;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_MOVE:
                controller.x = (int) event.getX();
                controller.y = (int) event.getY();
                invalidate();
                break;
        }
        return true;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        mPath.reset();

        mPath.moveTo(start.x, start.y);
        mPath.quadTo(controller.x, controller.y, end.x, end.y);
        mPath.close();

        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(Color.RED);
        mPaint.setStrokeWidth(30);
        mPaint.setTextSize(15);
        canvas.drawPoint(start.x, start.y, mPaint);
        canvas.drawPoint(end.x, end.y, mPaint);
        canvas.drawPoint(controller.x, controller.y, mPaint);

        mPaint.setColor(Color.BLACK);
        mPaint.setTextSize(25);
        canvas.drawText("结束点", end.x, end.y, mPaint);
        canvas.drawText("控制点", controller.x, controller.y, mPaint);
        canvas.drawText("起始点", start.x, start.y, mPaint);

        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(Color.BLUE);
        mPaint.setStrokeWidth(5);
        canvas.drawPath(mPath, mPaint);

        mPaint.setColor(Color.YELLOW);
        canvas.drawLine(start.x, start.y, controller.x, controller.y, mPaint);
        canvas.drawLine(end.x, end.y, controller.x, controller.y, mPaint);
    }
}
